import ApiService from './api';
import { Product, PaginationParams, PaginatedResponse } from '../types';

// 请求去重缓存
const requestCache = new Map<string, Promise<any>>();

// 生成请求缓存键
const generateCacheKey = (url: string, params: any) => {
  return `${url}?${JSON.stringify(params)}`;
};

// 带去重的请求方法
const requestWithDeduplication = async <T>(
  url: string,
  params: any,
  requestFn: () => Promise<T>,
  cacheDuration = 1000 // 1秒内的重复请求会被去重
): Promise<T> => {
  const cacheKey = generateCacheKey(url, params);

  // 如果有正在进行的相同请求，直接返回
  if (requestCache.has(cacheKey)) {
    console.log(`🔄 请求去重: ${cacheKey}`);
    return requestCache.get(cacheKey);
  }

  // 创建新请求
  const requestPromise = requestFn().finally(() => {
    // 请求完成后，延迟清除缓存
    setTimeout(() => {
      requestCache.delete(cacheKey);
    }, cacheDuration);
  });

  // 缓存请求
  requestCache.set(cacheKey, requestPromise);

  return requestPromise;
};

// 商品查询参数
export interface ProductQueryParams extends PaginationParams {
  keyword?: string;
  category?: string;
  shopId?: string;
  status?: 'active' | 'inactive' | 'out_of_stock';
  isFeatured?: boolean;
  minPrice?: number;
  maxPrice?: number;
}

// 商品创建/更新数据
export interface ProductFormData {
  name: string;
  description: string;
  price: number;
  originalPrice?: number;
  images: string[];
  category: string;
  shopId: string;
  stock: number;
  specifications: Record<string, string[]>;
  tags: string[];
  isFeatured: boolean;
  status: 'active' | 'inactive';
}

// 商品服务
export class ProductService {
  // 获取商品列表
  static async getProducts(params: ProductQueryParams): Promise<PaginatedResponse<Product>> {
    return requestWithDeduplication(
      '/admin/products',
      params,
      async () => {
        const response = await ApiService.get<any>('/admin/products', params);

        // 响应拦截器已经处理了success检查和数据提取
        // 直接使用response，它应该包含完整的后端响应
        const products = (response.data || []).map((item: any) => ({
          id: item.id || item._id,
          _id: item._id || item.id,
          name: item.name,
          description: item.description,
          price: item.price,
          originalPrice: item.originalPrice,
          images: item.images || [],
          category: item.category,
          brand: item.brand,
          shopId: item.shopId || '',
          shopName: item.shopName || '',
          stock: item.stock || 0,
          salesCount: item.salesCount || 0,
          status: item.status || 'active',
          specifications: item.specifications || {},
          tags: item.tags || [],
          isFeatured: item.isFeatured || false,
          createdAt: item.createdAt,
          updatedAt: item.updatedAt,
        }));

        return {
          data: products,
          total: response.total || response.pagination?.total || 0,
          page: response.pagination?.current || params.page || 1,
          limit: response.pagination?.pageSize || params.limit || 10,
          totalPages: response.pagination?.pages || Math.ceil((response.total || response.pagination?.total || 0) / (params.limit || 10)),
        };
      }
    );
  }

  // 获取商品详情
  static async getProduct(id: string): Promise<Product> {
    const response = await ApiService.get<any>(`/admin/products/${id}`);

    const item = response.data;
    return {
      id: item.id || item._id,
      _id: item._id || item.id,
      name: item.name,
      description: item.description,
      price: item.price,
      originalPrice: item.originalPrice,
      images: item.images || [],
      category: item.category,
      brand: item.brand,
      shopId: item.shopId || '',
      shopName: item.shopName || '',
      stock: item.stock || 0,
      salesCount: item.salesCount || 0,
      status: item.status || 'active',
      specifications: item.specifications || {},
      tags: item.tags || [],
      isFeatured: item.isFeatured || false,
      createdAt: item.createdAt,
      updatedAt: item.updatedAt,
    };
  }

  // 创建商品
  static async createProduct(data: ProductFormData): Promise<Product> {
    // 转换前端数据格式到后端格式
    const backendData = {
      name: data.name,
      description: data.description,
      price: data.price,
      originalPrice: data.originalPrice,
      images: data.images,
      mainImage: data.images && data.images.length > 0 ? data.images[0] : undefined, // 设置主图为第一张图片
      category: data.category,
      brand: data.brand,
      shop: data.shopId,
      stock: data.stock,
      specifications: data.specifications,
      tags: data.tags,
      isFeatured: data.isFeatured,
    };

    const response = await ApiService.post<any>('/admin/products', backendData);

    const item = response.data;
    return {
      id: item.id || item._id,
      _id: item._id || item.id,
      name: item.name,
      description: item.description,
      price: item.price,
      originalPrice: item.originalPrice,
      images: item.images || [],
      category: item.category,
      brand: item.brand,
      shopId: item.shopId || '',
      shopName: item.shopName || '',
      stock: item.stock || 0,
      salesCount: item.salesCount || 0,
      status: item.status || 'active',
      specifications: item.specifications || {},
      tags: item.tags || [],
      isFeatured: item.isFeatured || false,
      createdAt: item.createdAt,
      updatedAt: item.updatedAt,
    };
  }

  // 更新商品
  static async updateProduct(id: string, data: Partial<ProductFormData>): Promise<Product> {
    // 转换前端数据格式到后端格式
    const backendData: any = {};
    if (data.name) backendData.name = data.name;
    if (data.description) backendData.description = data.description;
    if (data.price !== undefined) backendData.price = data.price;
    if (data.originalPrice !== undefined) backendData.originalPrice = data.originalPrice;
    if (data.images) {
      backendData.images = data.images;
      // 自动设置mainImage为第一张图片
      if (data.images.length > 0) {
        backendData.mainImage = data.images[0];
      }
    }
    if (data.category) backendData.category = data.category;
    if (data.brand) backendData.brand = data.brand;
    if (data.shopId) backendData.shop = data.shopId;
    if (data.stock !== undefined) backendData.stock = data.stock;
    if (data.specifications) backendData.specifications = data.specifications;
    if (data.tags) backendData.tags = data.tags;
    if (data.isFeatured !== undefined) backendData.isFeatured = data.isFeatured;

    const response = await ApiService.put<any>(`/admin/products/${id}`, backendData);

    const item = response.data;
    return {
      id: item.id || item._id,
      _id: item._id || item.id,
      name: item.name,
      description: item.description,
      price: item.price,
      originalPrice: item.originalPrice,
      images: item.images || [],
      category: item.category,
      brand: item.brand,
      shopId: item.shopId || '',
      shopName: item.shopName || '',
      stock: item.stock || 0,
      salesCount: item.salesCount || 0,
      status: item.status || 'active',
      specifications: item.specifications || {},
      tags: item.tags || [],
      isFeatured: item.isFeatured || false,
      createdAt: item.createdAt,
      updatedAt: item.updatedAt,
    };
  }

  // 删除商品
  static async deleteProduct(id: string): Promise<void> {
    await ApiService.delete<any>(`/admin/products/${id}`);
  }

  // 批量删除商品
  static async batchDeleteProducts(ids: string[]): Promise<void> {
    await ApiService.post<any>('/admin/products/batch-delete', { ids });
  }

  // 批量更新商品
  static async batchUpdateProducts(ids: string[], data: any): Promise<void> {
    await ApiService.post<any>('/admin/products/batch-update', { ids, data });
  }

  // 更新商品状态
  static async updateProductStatus(id: string, status: 'active' | 'inactive'): Promise<Product> {
    return await ApiService.patch<Product>(`/admin/products/${id}/status`, { status });
  }

  // 批量更新商品状态
  static async updateProductsStatus(ids: string[], status: 'active' | 'inactive'): Promise<void> {
    await ApiService.post('/admin/products/batch-status', { ids, status });
  }

  // 设置商品为推荐
  static async setProductFeatured(id: string, isFeatured: boolean): Promise<Product> {
    return await ApiService.patch<Product>(`/admin/products/${id}/featured`, { isFeatured });
  }

  // 更新商品库存
  static async updateProductStock(id: string, stock: number): Promise<Product> {
    return await ApiService.patch<Product>(`/admin/products/${id}/stock`, { stock });
  }

  // 获取商品分类列表
  static async getCategories(): Promise<string[]> {
    return await ApiService.get<string[]>('/admin/products/categories');
  }

  // 获取商品标签列表
  static async getTags(): Promise<string[]> {
    return await ApiService.get<string[]>('/admin/products/tags');
  }

  // 获取热门商品
  static async getPopularProducts(limit: number = 10): Promise<Product[]> {
    return await ApiService.get<Product[]>('/admin/products/popular', { limit });
  }

  // 获取推荐商品
  static async getFeaturedProducts(limit: number = 10): Promise<Product[]> {
    return await ApiService.get<Product[]>('/admin/products/featured', { limit });
  }

  // 获取低库存商品
  static async getLowStockProducts(threshold: number = 10): Promise<Product[]> {
    return await ApiService.get<Product[]>('/admin/products/low-stock', { threshold });
  }

  // 商品搜索建议
  static async getSearchSuggestions(keyword: string): Promise<string[]> {
    return await ApiService.get<string[]>('/admin/products/search-suggestions', { keyword });
  }

  // 导出商品数据
  static async exportProducts(params: ProductQueryParams): Promise<void> {
    await ApiService.download('/admin/products/export', 'products.xlsx');
  }

  // 导入商品数据
  static async importProducts(file: File): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    return await ApiService.upload('/admin/products/import', file);
  }

  // 获取商品销售统计
  static async getProductSalesStats(id: string, period: 'day' | 'week' | 'month' = 'month'): Promise<{
    totalSales: number;
    totalRevenue: number;
    salesData: Array<{
      date: string;
      sales: number;
      revenue: number;
    }>;
  }> {
    return await ApiService.get(`/admin/products/${id}/sales-stats`, { period });
  }

  // 复制商品
  static async duplicateProduct(id: string): Promise<Product> {
    return await ApiService.post<Product>(`/admin/products/${id}/duplicate`);
  }

  // 获取商品评价统计
  static async getProductReviews(id: string, params: PaginationParams): Promise<PaginatedResponse<any>> {
    return await ApiService.get<PaginatedResponse<any>>(`/admin/products/${id}/reviews`, params);
  }

  // 获取商品访问统计
  static async getProductViewStats(id: string, period: 'day' | 'week' | 'month' = 'month'): Promise<{
    totalViews: number;
    uniqueViews: number;
    viewsData: Array<{
      date: string;
      views: number;
      uniqueViews: number;
    }>;
  }> {
    return await ApiService.get(`/admin/products/${id}/view-stats`, { period });
  }

  // 批量更新商品状态
  static async batchUpdateStatus(ids: string[], status: string): Promise<void> {
    return await ApiService.post('/admin/products/batch-status', { ids, status });
  }
}

export default ProductService;
